<template>
  <view class="warp">
    <u-navbar>
      <view class="slot-wrap flex_c">
        剩余时间：
        <u-count-down
          :timestamp="timestamp"
          @end="timestampEnd"
          @change="timestampChange"
        ></u-count-down>
      </view>
      <template #right>
        <view class="right" @click="clickCollection">
          <view
            class="iconfont"
            :class="
              list[current] && list[current].boolCollec === 0
                ? 'icon-31shoucang'
                : 'icon-shoucangfill'
            "
          ></view>
        </view>
      </template>
    </u-navbar>
    <!-- 内容 -->
    <view class="content" :style="{ height: contentHeight - padHeight + 'px' }">
      <swiper
        :current="current"
        :duration="500"
        @change="swiperChange"
        class="swiper"
      >
        <swiper-item v-for="item in list" :key="item.id">
          <view class="swiper-item">
            <view class="title_warp">
              <view class="type">
                {{ item.questionType == 0 ? "单选" : "多选" }}
              </view>
              <rich-text :nodes="item.content" class="title" />
            </view>
            <view class="choose_warp">
              <template v-if="item.questionType === 0">
                <view
                  class="choose_item flex"
                  v-for="(v, i) in item.optionJson"
                  :key="i"
                  :class="{
                    correct:
                      item.isTrue &&
                      item.chooseList &&
                      item.chooseList[0] - 1 === i,
                    fail:
                      item.isTrue === false &&
                      item.chooseList &&
                      item.chooseList[0] - 1 === i,
                  }"
                  @click="chooseItem(i + 1)"
                >
                  {{ i + 1 }} <rich-text :nodes="v"></rich-text>
                </view>
              </template>

              <template v-if="item.questionType === 1">
                <view
                  class="choose_item flex"
                  v-for="(v, i) in item.optionJson"
                  :key="i"
                  :class="{
                    correct:
                      item.chooseList.include(i) &&
                      item.standardAnswer.include(i),
                    fail:
                      item.chooseList.include(i) &&
                      !item.standardAnswer.include(i),
                  }"
                  @click="chooseItem(i + 1)"
                >
                  {{ i + 1 }} <rich-text :nodes="v"></rich-text>
                </view>
              </template>
            </view>
            <view class="next_warp flex_b">
              <template
                v-if="item.isTrue === undefined && item.questionType === 1"
              >
                <view></view>
                <view class="next_btn" @click="isTrue(item)">提交本题</view>
              </template>
              <template v-else>
                <view class="next_btn" @click="clickNext(-1)">上一题</view>
                <view class="next_btn" @click="clickNext(1)">下一题</view>
              </template>
            </view>

            <template v-if="item.isTrue !== undefined">
              <view class="answer_warp"> 答案:{{ item.answer }} </view>
              <view class="parsing">
                解析: {{ item.userStandardAnswer ? "" : "无" }}
                <rich-text :nodes="item.userStandardAnswer" />
              </view>
            </template>
          </view>
        </swiper-item>
      </swiper>
    </view>
    <!-- 底部工具 -->
    <view class="pad_bot safety">
      <view class="bottom_tools flex_b">
        <view class="left_btn" @click="submit">交卷</view>
        <view class="center_warp flex_b">
          <view class="true_warp flex_c">
            <view class="iconfont icon-True_circle"></view>
            {{ testObj.correct }}
          </view>
          <view class="true_warp failcolor flex_c">
            <view class="iconfont icon-False_circle"></view>
            {{ testObj.fail }}
          </view>
        </view>
        <view class="right_warp flex_c" @click="clickshowPopup">
          <view class="iconfont icon-more"></view>
          {{ current + 1 }}/{{ total || list.length }}
        </view>
      </view>
    </view>

    <!-- <bottom-safety class="bottomSafety" /> -->
    <!-- 弹出层 -->
    <u-popup v-model="showPopup" mode="bottom" height="80%">
      <view class="bottom_tools flex_b">
        <view class="left_btn" @click="submit">交卷</view>
        <view class="center_warp flex_b">
          <view class="true_warp flex_c">
            <view class="iconfont icon-True_circle"></view>
            {{ testObj.correct }}
          </view>
          <view class="true_warp failcolor flex_c">
            <view class="iconfont icon-False_circle"></view>
            {{ testObj.fail }}
          </view>
        </view>
        <view class="right_warp flex_c" @click="closePopup">
          <view class="iconfont icon-more"></view>
          {{ current + 1 }}/{{ total || list.length }}
        </view>
      </view>
      <view class="change_current flex">
        <view
          class="current_item pend flex_c"
          v-for="(item, index) in list"
          :key="item.id"
          :class="{ correct: item.isTrue, fail: item.isTrue === false }"
          @click="chooseCurrent(index)"
          >{{ index + 1 }}</view
        >
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  chapterExerciseQuestionSubmit,
  chapterExerciseQuestion,
  onlineEvaluationQuestionSubmit,
  getQuestionTypeList,
  getQuestionRecord,
} from "@/api/course";
import { setCollecQuestion } from "@/api/common";
import { setHis } from "@/utils/util";
export default {
  data() {
    return {
      questionType: "", // 0章节练习 1在线评测
      timestamp: 60 * 60,
      list: [],
      total: 0,
      current: 0,
      contentHeight: 500,
      padHeight: 0,
      testObj: {
        correct: 0,
        fail: 0,
      },
      showPopup: false,
      itemObj: {},
    };
  },
  onLoad(options) {
    const item = JSON.parse(options.item);
    this.itemObj = item;
    this.current = item.indexId || 0;
    if (options.questionType) {
      // 错题本和题目收藏
      this.getList({
        courseQuestionSectionId: options.courseQuestionSectionId,
        questionType: options.questionType,
      });
    } else if (options.coursePackageId) {
      // 根据最近练习
      this.getList({
        coursePackageId: options.coursePackageId,
        id: options.id,
      });
    } else {
      this.chapterExerciseQuestion();
    }
  },
  onReady() {
    this.$nextTick(() => {
      const query = uni.createSelectorQuery(this);
      query
        .select(".u-navbar")
        .boundingClientRect((rect) => {
          this.contentHeight =
            uni.getSystemInfoSync().windowHeight - rect.height - 50;
        })
        .exec();
      query
        .select(".bottomSafety")
        .boundingClientRect()
        .exec((res) => {
          this.padHeight = res[0].height;
        });
    });
  },

  methods: {
    // 获取错题
    getList(params) {
      const fun = params.questionType ? getQuestionTypeList : getQuestionRecord;
      fun(params).then((res) => {
        this.dispose(res);
      });
    },
    // 收藏
    clickCollection() {
      const { itemObj, current, list } = this;
      const params = {
        coursePackageId: itemObj.coursePackageId,
        courseQuestionSectionId: itemObj.courseQuestionSectionId,
        questionId: list[current].id,
        boolCollect: list[current].boolCollec === 0 ? 1 : 0,
      };
      setCollecQuestion(params).then((res) => {
        this.list[current].boolCollec = list[current].boolCollec === 0 ? 1 : 0;
      });
    },
    // 倒计时结束
    timestampEnd() {
      this.$ShowToast({
        title: "答题时间到,系统自动提交",
      });
      this.config();
    },
    timestampChange(e) {
      this.timestamp = e;
    },
    // 提交
    submit() {
      const {
        total,
        testObj: { correct, fail },
      } = this;
      if (correct + fail < total) {
        this.$ShowModal({
          content: "当前题目未答完,是否交卷?",
        }).then((res) => {
          if (!res) return;
          this.config();
        });
      } else {
        this.config();
      }
    },
    // 发送提交请求
    config() {
      const { list, itemObj, timestamp, current } = this;
      let params = {
        coursePackageId: itemObj.coursePackageId,
        duration: setHis(60 * 60 - timestamp),
        id: itemObj.id,
        indexId: current,
      };
      if (itemObj.questionType === 0) {
        // 	0章节练习 1在线评测
        params.courseQuestionSectionId = itemObj.courseQuestionSectionId;
      }
      const submitAnswerVos = [];
      list.forEach((v, i) => {
        let obj = {
          questionId: v.id,
          userAnswer: v.chooseList,
        };
        submitAnswerVos.push(obj);
      });
      params.submitAnswerVos = submitAnswerVos;
      this.questionSubmit(params).then((res) => {
        this.$u.route("/pages/test_results/test_results", {
          res: JSON.stringify(res),
        });
      });
    },
    clickshowPopup() {
      this.showPopup = true;
    },
    closePopup() {
      this.showPopup = false;
    },
    chooseCurrent(index) {
      this.current = index;
      this.closePopup();
    },
    // 选额答案
    chooseItem(index) {
      const { list, current } = this;
      if (list[current].isTrue !== undefined) {
        this.$ShowToast({
          title: "答案已提交,无法修改",
          mask: false,
        });
        return;
      }

      if (list[current].questionType === 0) {
        // 单选
        list[current].chooseList = [index];
        this.isTrue(list[current]);
      } else {
        // 多选
        let choose = list[current].chooseList ? list[current].chooseList : [];
        const i = choose.indexOf(index);
        if (i > -1) {
          choose.splice(i, 1);
        } else {
          choose.push(index);
        }
        list[current].chooseList = choose.sort((a, b) => {
          return a - b;
        });
      }
    },
    // 判断对错
    isTrue(obj) {
      if (obj.standardAnswer.toString() == obj.chooseList.toString()) {
        obj.isTrue = true;
        this.testObj.correct += 1;
      } else {
        obj.isTrue = false;
        this.testObj.fail += 1;
      }
      this.list[this.current] = obj;
    },
    swiperChange(e) {
      this.current = e.detail.current;
    },
    clickNext(num) {
      if (num < 0 && this.current == 0) {
        this.$ShowToast({
          title: "当前为第一题",
          mask: false,
        });
        return;
      }
      if (this.current == this.total - 1 && num > 0) {
        this.$ShowToast({
          title: "当前最后一题",
          mask: false,
        });
        return;
      }
      this.current += num;
    },
    // 获取题目
    chapterExerciseQuestion() {
      let params = {
        id: this.itemObj.courseQuestionSectionId,
      };
      chapterExerciseQuestion(params).then((res) => {
        this.dispose(res);
      });
    },
    // 处理
    dispose(res) {
      res.list.forEach((v) => {
        v.optionJson = JSON.parse(v.optionJson);
        v.standardAnswer = JSON.parse(v.standardAnswer);
        v.answer = this.getAnswer(v.standardAnswer);
      });
      this.list = res.list;
      this.total = res.total;
    },
    // 答案
    getAnswer(arr) {
      const arrE = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
      let res = arr.map((v) => arrE[v - 1]);
      return res.join(" , ");
    },
  },
  computed: {
    questionSubmit() {
      return this.itemObj.questionType === 0
        ? chapterExerciseQuestionSubmit
        : onlineEvaluationQuestionSubmit;
    },
  },
};
</script>

<style lang="scss">
.warp {
  width: 100vw;
  height: 100vh;
  .u-navbar {
    .slot-wrap {
      flex: 1;
    }

    .right {
      margin-right: 30upx;
      .iconfont {
        font-size: 40upx;
      }
    }
  }
  .content {
    .swiper {
      width: 100%;
      height: 100%;
      .swiper-item {
        padding: 20upx;
        width: 100%;
        height: 100%;
        .title_warp {
          width: 100%;
          display: flex;
          .type {
            padding: 0 20upx;
            background: #0499fd;
            flex-shrink: 0;
            font-size: 24upx;
            height: 50upx;
            line-height: 50upx;
            color: #fff;
            border-radius: 10upx;
          }
          .title {
            flex: 1;
            margin-left: 10upx;
          }
        }
        .choose_warp {
          padding: 0 20upx;
          .choose_item {
            width: 100%;
            font-size: 32upx;
            font-weight: 500;
            margin-top: 30upx;
          }
        }
        .next_warp {
          margin-top: 30upx;
          .next_btn {
            padding: 11upx 30upx;
            border: 5upx solid #007acc;
            border-radius: 40upx;
          }
        }
        .answer_warp {
          margin-top: 30upx;
          padding: 20upx;
          background: #03c2e6;
          font-size: 28upx;
          color: #fff;
          font-weight: 600;
          border-radius: 20upx;
        }
        .parsing {
          margin-top: 30upx;
        }
      }
    }
  }
  .pad_bot {
    position: fixed;
    width: 100vw;
    left: 0;
    bottom: 0;
  }
  .bottom_tools {
    background: #fff;
    padding: 0 20upx;
    height: 50px;
    border-bottom: 2upx solid #ccc;
    .left_btn {
      padding: 15upx 40upx;
      background: #007acc;
      color: #fff;
      border-radius: 30upx;
    }
    .iconfont {
      margin-right: 10upx;
      font-size: 40upx;
    }
    .center_warp {
      .true_warp {
        color: #007acc;
      }
      .failcolor {
        color: red;
        margin-left: 20upx;
      }
    }
    .right_warp {
    }
  }
  .change_current {
    width: 100%;
    flex-wrap: wrap;
    .current_item {
      width: 92upx;
      height: 92upx;
      margin: 30upx;
      border-radius: 15upx;
      font-size: 32upx;
      flex-shrink: 0;
    }
  }
  .pend {
    background-color: #f5f5f5;
  }
  .correct {
    color: #007acc;
    background-color: #829db0;
  }
  .fail {
    color: red;
    background-color: #7d5a51;
  }
}
</style>
